package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import pojo.User;
import dao.UserDao;
import dao.impl.UserDaoImpl;

public class InfoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
	
	private UserDao userDao;
	private DateFormat dateFormat;
       
    public InfoServlet() {
        super();
        userDao = new UserDaoImpl();
        dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		if (user==null) {
			response.sendRedirect("error?info=you should login");
		}else{
			StringBuilder result = new StringBuilder();
			result.append("<h1>users info</h1>");
			result.append("<table style='border:1px solid #000'><tr><td>username</td><td>sal</td><td>birth</td><td>sex</td><td>avatar</td></tr>");
			List<User> users = userDao.findAll();
			for(User user1:users){
				result.append("<tr><td>"+user1.getUname()+"</td><td>"+user1.getSal()+"</td><td>"+dateFormat.format(user1.getBirth())+"</td><td>"+user1.isSex()+"</td><td><image src='avatar?uid="+user1.getId()+"'</td></tr>");
			}
			result.append("</table>");
			PrintWriter writer = response.getWriter();
			writer.write(result.toString());
			writer.close();
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
